package engine.services.impl;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringReader;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.AbstractHandler;

public class JettyWebServer {

	Runnable server;
	static int port = 16123;
	Server jetty;
	public static String URL = "http://localhost:" + port;
	
	static Handler handler;
	static {
		handler= new AbstractHandler() {
			
		    @Override
		    public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
				if (System.out != null)
					System.out.println("********** Server request: " + target + " **************");
				if (target.endsWith("html") || target.endsWith("xml")) {
					if (target.endsWith("html")) {
				        response.setContentType("text/html;charset=utf-8");																
					} else  {
				        response.setContentType("text/xml;charset=utf-8");																
					}
			        FileReader fr = new FileReader("src/test/resources/webserver_pages/"+target);
			        BufferedReader br = new BufferedReader(fr);
			        String line = null;
			        while ((line = br.readLine()) != null) {
				        response.getWriter().println(line);			        	
			        }
				} else {
					//			        response.setContentType("image/gif");	
			        response.setContentType("image/gif"); 
			        FileInputStream fis = new FileInputStream("src/test/resources/webserver_pages/"+target);
			        OutputStream out = response.getOutputStream();
			        IOUtils.copy(fis, out);
				}
		        response.setStatus(HttpServletResponse.SC_OK);
		        baseRequest.setHandled(true);
		    }
		};
	}
	
	public JettyWebServer() {
		server = new Runnable() {		
			@Override
			public void run() {
				jetty = new Server(port);
				try {
					jetty.setHandler(handler);
					jetty.start();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		};
		try {
			server.run();	
			if (System.out != null)
				System.out.println("********** Server started **************");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void stop() throws Exception {
		jetty.stop();
		if (System.out != null) {
			System.out.println("********** Server stopped **************");			
		}
	}
}
